package com.user.service;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;

import com.bean.Common;
import com.user.dao.CommonDao;
@Service
public class CommonServiceImp implements CommonService {
    @Autowired
    private CommonDao commonDao;
	
	public String AdminInsertCommon(Common common, Model model, HttpServletRequest req, MultipartFile mypic) {
		// TODO Auto-generated method stub
		String gpic=uploadOneFile(mypic,req);
		common.setCommon_img(gpic);	
		int i=commonDao.insertCommon(common);
		if(i>0) {
			model.addAttribute("mess","操作成功");
			return "forward:UserSelectMyCommon";
		}else {
			return "admin/fail";
		}
	}

	

	
	public String UserSelectCommon(Model model) {
		// TODO Auto-generated method stub
		List<Map<String,Object>>list=commonDao.selectCommon();
		model.addAttribute("list",list);
		return "user/commonshow";
	}
	
	
	public String uploadOneFile(MultipartFile myfile,
			 HttpServletRequest request) {
		 String realpath=request.getServletContext().
				 getRealPath("images");
		 File pathfile=new File(realpath);
		 if(!pathfile.exists()) {
			 pathfile.mkdirs();
		 }
		 String filename=myfile.getOriginalFilename();
		 String suffixList = "jpg,gif,png,ico,bmp,jpeg";
		 String type=filename.substring
				 (filename.lastIndexOf(".")+1,filename.length());
		 if(suffixList.contains(type.toLowerCase())) {
			//******************************************//
			 File tagrgetFile=new File(realpath,filename);
			 try {
				myfile.transferTo(tagrgetFile);
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return filename ;
		 }else {
			return null ;
		 }
	  }

	
	public String UserSelectMyCommon(Model model, int uid) {
		// TODO Auto-generated method stub
		List<Common>list=commonDao.UserSelectMyCommon(uid);
		model.addAttribute("list",list);
		return "user/mycommonshow";
	}

	
	public String userDeleteCommon(int common_id, Model model) {
		// TODO Auto-generated method stub
		int i=commonDao.AdminDeleteCommon(common_id);
		if(i>0) {
			return "forward:UserSelectMyCommon";
		}else {
			return "user/fail";
		}
	}
}
